<template>
	<view>
		<u-sticky bgColor="#fff">
			<view class="blank10"></view>
			<view class="wrapper flex">
				<view class="flex-1 font-bold">
					{{date}}
				</view>
				<!-- <view class="text-gray">
					筛选项目点：
				</view> -->
				<view class="">
					<u-button type="info" size="small" text="筛选" @click="openFilter"></u-button>
					<!-- <picker @change="bind_purchase_unit_change" :range="material_purchase_unit_category" range-key="name" :data-name="index">
						<u-button type="info" size="small" text="全部"></u-button>
					</picker> -->
				</view>
			</view>
			<view class="blank10"></view>
			<u-line></u-line>
			<search @choose="chooseSearch" :data="material_item" page="purchaseOrder" namekey="mname" :add="false"></search>
			<u-line></u-line>
			<view class="flex bg-gray">
				<template v-for="col in tableHd">
					<view class="col-item font-24" :style="[col.style]">
						{{col.title}}
					</view>
				</template>
			</view>
			<!-- <u-line></u-line>
			<view class="blank20"></view>
			<u-row justify="space-between" gutter="3">
				<template v-for="col in tableHd">
					<u-col :span="col.span">
						<view class="text-center text-gray font-24">
							{{col.title}}
						</view>
					</u-col>
				</template>
			</u-row>
			<view class="blank20"></view>
			<u-line></u-line> -->
		</u-sticky>
		<view class="">
			<u-checkbox-group v-model="checkboxValue" placement="column" @change="checkboxChange">
				<template v-for="(v,index) in list">
					<view class="bgw">
						<view class="flex">
							<template v-for="col in tableHd">
								<view class="col-item" :style="[col.style]" v-if="col.key == 'mm_id_name'">
									<u-checkbox :key="index" :name="index" :label="v[col.key]" activeColor="#675f91" shape="circle"
										labelSize="14"></u-checkbox>
								</view>
								<view class="col-item" :style="[col.style]" v-else-if="col.key == 'purchase_unit_qty'">
									<input v-model="purchase_unit_qty[v.mm_id]" type="number" placeholder="请输入" :maxlength="8"
										class="input_border_bottom text-center" @input="value_input" @blur="value_blur" :data-name="index"
										:data-mmid="v.mm_id" data-key="purchase_unit_qty" />
								</view>
								<view class="col-item" :style="[col.style]" v-else-if="col.key == 'purchase_unit_id'">
									<picker @change="bind_purchase_unit_change" :range="purchase_unit_mmid_obj[v.mm_id]" range-key="label"
										:data-name="index" :data-mmid="v.mm_id">
										<view class="flex input_border_bottom">
											<view class="flex-1 text-center">
												{{material_purchase_unit_category_obj[v.purchase_unit_id]?material_purchase_unit_category_obj[v.purchase_unit_id].name:''}}
											</view>
											<view class="ml5">
												<u-icon name="arrow-down" color="#999999" size="14"></u-icon>
											</view>
										</view>
									</picker>
								</view>
								<view class="col-item" :style="[col.style]" v-else>
									{{v[col.key]}}
								</view>
							</template>
						</view>
						<u-line dashed></u-line>
						<view class="flex">
							<view class="col-item flex" style="width: 200rpx;">
								<view class="">
									￥
								</view>
								<view class="flex-1">
									<input v-model="purchase_unit_price[v.mm_id]" type="number" placeholder="请输入" :maxlength="8"
										class="input_border_bottom text-center" @input="value_input" @blur="value_blur" :data-name="index"
										:data-mmid="v.mm_id" data-key="purchase_unit_price" />
								</view>
								<view class="">
									/{{material_purchase_unit_category_obj[v.purchase_unit_id]?material_purchase_unit_category_obj[v.purchase_unit_id].name:''}}
								</view>
							</view>
							<view class="col-item text-center" style="width: 200rpx;">
								￥{{price[v.mm_id]||0|formatPrice}}
							</view>
							<view class="col-item flex-1">
								<view class="flex input_border_bottom" @click="openMsupplierPicker" :data-name="index">
									<view class="flex-1 text-center">
										{{msupplierObj[v.supplier_id]?msupplierObj[v.supplier_id].supplier_nick_name:'请选择'}}
									</view>
									<view class="ml5">
										<u-icon name="arrow-down" color="#999999" size="14"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="blank20"></view>

					<!-- 	<view class="">
						<u-row justify="space-between" gutter="3">
							<template v-for="col in tableHd">
								<u-col :span="col.span">
									<view class="text-center" style="padding-left: 10px;" v-if="col.key == 'mm_id_name'">
										<u-checkbox :key="index" :name="index" :label="v[col.key]" activeColor="#675f91" shape="circle" labelSize="14"></u-checkbox>
									</view>
									<view class="text-center" v-else-if="col.key == 'purchase_unit_qty'">
										{{v[col.key]}}{{v.purchase_unit_id_name}}
									</view>
									<view class="text-center" v-else>
										{{v[col.key]}}
									</view>
								</u-col>
							</template>
						</u-row>
						<view class="blank20"></view>
						<u-line dashed></u-line>
					</view> -->
				</template>
			</u-checkbox-group>
		</view>

		<view class="blank"></view>
		<view class="fixed-bottom bgw">
			<u-line></u-line>
			<view class="flex">
				<view class="flex-1" style="padding-left: 15px;">
					<u-checkbox-group placement="column" v-model="checkboxAllValue" @change="checkboxAllChange">
						<u-checkbox :key="0" :name="0" label="全选" activeColor="#675f91" shape="circle"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view class="ml15 mr15">
					<text class="font-22 text-light-gray">金额：</text>
					<text class="text-red">￥{{sum_price}}</text>
				</view>
				<view class="btn-confirm" @click="order">
					下单
				</view>
			</view>
		</view>

		<msupplierPicker :show="msupplierPickerShow" :msupplier="msupplier" @confirm="msupplierPickerConfirm"
			@cancel="msupplierPickerCancel" v-if="msupplier.length>0"></msupplierPicker>

		<u-popup :show="filterPopupShow" @close="filterPopupClose" @open="filterPopupOpen" mode="top" :closeable="true">
			<view class="flex justify-center" style="background-color: #f5f5f5;height: 44px;">
				<view>
					筛选
				</view>
			</view>
			<view class="wrapper">
				<view class="">
					<view class="blank20"></view>
					<view class="">
						核算单位
					</view>
					<view class="blank20"></view>
					<u-checkbox-group v-model="filter.cost_center" placement="row">
						<view class="flex" style="flex-wrap: wrap;">
							<template v-for="v in cost_center_arr">
								<view class="" style="margin: 15upx;">
									<u-checkbox activeColor="#675f91" :label="v.label" :name="v.value"></u-checkbox>
								</view>
							</template>
						</view>
					</u-checkbox-group>
				</view>
				<view class="blank20"></view>
				<u-line></u-line>
				<view class="">
					<view class="blank20"></view>
					<view class="">
						客户组
					</view>
					<view class="blank20"></view>
					<u-checkbox-group v-model="filter.cus_group" placement="row">
						<view class="flex" style="flex-wrap: wrap;">
							<template v-for="v in cus_group_arr">
								<view class="" style="margin: 15upx;">
									<u-checkbox activeColor="#675f91" :label="v.label" :name="v.value"></u-checkbox>
								</view>
							</template>
						</view>
					</u-checkbox-group>
				</view>
			</view>
			<view class="blank20"></view>
			<view class="wrapper" style="background-color: #f5f5f5;">
				<view class="blank20"></view>
				<u-row justify="space-between" gutter="10">
					<u-col span="6">
						<u-button type="info" text="关闭" @click="closeFilter"></u-button>
					</u-col>
					<u-col span="6">
						<u-button type="primary" text="确定" @click="saveFilter"></u-button>
					</u-col>
				</u-row>

				<view class="blank20"></view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		chef_purchase_record,
		get_user_session_id,
		purchase_request_delete,
		org_pr_list,
		purchaser_place_order,
		po_pr_record,
		material_create_edit,
		purchase_material_item
	} from '@/common/api.js';
	import msupplierPicker from '@/pagesA/components/msupplier-picker.vue';
	import search from "@/components/search.vue";
	export default {
		components: {
			msupplierPicker,
			search
		},
		data() {
			return {
				org_pr_id: 0,
				date: '',
				allList: [],
				list: [],
				tableHd: [{
						title: '食材',
						key: 'mm_id_name',
						style: {
							flex: 1
						},
					},
					{
						title: '数量',
						key: 'purchase_unit_qty',
						style: {
							width: '150rpx',
							'text-align': 'center'
						},
					},
					{
						title: '单位',
						key: 'purchase_unit_id',
						style: {
							width: '150rpx',
							'text-align': 'center'
						},
					},
					{
						title: '送货至',
						key: 'cus_group_id_name',
						style: {
							width: '220rpx'
						},
					},
					// {
					// 	title: '供应商',
					// 	key: 'supplier_id_name',
					// 	span: 3
					// }
				],
				checkboxValue: [],
				checkboxAllValue: [0],

				msupplier: [],
				msupplierObj: {},
				msupplierPickerShow: false,
				msupplierPickerKey: '',
				purchase_unit_qty: {},
				purchase_unit_price: {},
				price: {},
				purchase_unit_mmid_obj: {},
				material_purchase_unit_category: [],
				material_purchase_unit_category_obj: {},
				material_item: [],
				material_obj: {},
				cus_group_arr: [],
				cost_center_arr: [],
				filterPopupShow: false,
				filter: {
					cost_center: [],
					cus_group: []
				},
				old_filter: {
					cost_center: [],
					cus_group: []
				}
			}
		},
		computed: {
			sum_price() {
				let num = 0;
				let list = this.list.filter((v, i) => this.checkboxValue.includes(i));
				list.forEach(v => {
					if (v.purchase_unit_price && v.purchase_unit_qty) {
						num += v.purchase_unit_price * v.purchase_unit_qty
					}
				});
				num = this.formatPrice(num);
				return num;
			}
		},
		methods: {
			openFilter() {
				this.filterPopupShow = true;
			},
			filterPopupClose() {
				this.closeFilter();
			},
			filterPopupOpen() {

			},
			saveFilter() {
				// console.log(this.filter);
				this.old_filter = JSON.parse(JSON.stringify(this.filter));
				this.filterPopupShow = false;
				this.list = this.allList.filter(v => {
					let cost_center_flag = this.filter.cost_center.includes(v.cost_center_id);
					let cus_group_flag = this.filter.cus_group.includes(v.cus_group_id);
					return cost_center_flag && cus_group_flag
				})
			},
			closeFilter() {
				this.filter = JSON.parse(JSON.stringify(this.old_filter));
				this.filterPopupShow = false;
			},
			chooseSearch(id) {
				let material = this.material_obj[id];
				let mm_id = material.mm_id[0];
				if (this.allList.filter(v => v.mm_id == mm_id).length > 0) {
					uni.$u.toast('已有食材：' + material.mname);
					return;
				}
				// console.log(material);
				// console.log(this.msupplier);
				let supplier_id = '';
				try {
					supplier_id = this.msupplier.find(v => v.data.id == material.default_msupplier_id[0]).id;
				} catch (e) {}

				let item = {
					id: 0,
					mm_id: mm_id,
					mm_id_name: material.mname,
					purchase_unit_qty: 1,
					purchase_unit_price: material.purchase_unit_price,
					purchase_unit_id: material.purchase_unit_id[0],
					need_date: this.date,
					supplier_id: supplier_id,
					mbatch_int: 0,
					org_pr_pending_id: [],
					cost_center_id: 0,
					cost_center_id_name: '',
					cus_group_id: 0,
					cus_group_id_name: '',
				}
				if (this.cost_center_arr.length > 0) {
					item.cost_center_id = this.cost_center_arr[0].value;
					item.cost_center_id_name = this.cost_center_arr[0].label;
				}
				if (this.cus_group_arr.length > 0) {
					item.cus_group_id = this.cus_group_arr[0].value;
					item.cus_group_id_name = this.cus_group_arr[0].label;
				}
				let length = this.list.push(item);
				this.purchase_unit_price[mm_id] = item.purchase_unit_price;
				this.purchase_unit_qty[mm_id] = 1;
				this.price[mm_id] = this.purchase_unit_qty[mm_id] * this.purchase_unit_price[mm_id];
				this.allList.push(item);
				this.checkboxValue.push(length - 1);
			},
			value_input(e) {

			},
			value_blur(e) {

				let index = e.target.dataset.name;
				let mmid = e.target.dataset.mmid;
				let key = e.target.dataset.key;
				let num = this.formatPrice(e.detail.value);

				if (key == 'purchase_unit_qty') {
					// console.log(key);
					// console.log(num);
					// console.log(mmid);
					this.$set(this.purchase_unit_qty, mmid, num);
				}
				if (key == 'purchase_unit_price') {
					this.$set(this.purchase_unit_price, mmid, num);
				}
				this.list[index][key] = num;
				this.price[mmid] = this.purchase_unit_qty[mmid] * this.purchase_unit_price[mmid];
				this.$forceUpdate();
				this.updataAllList();
			},
			bind_purchase_unit_change(e) {
				let index = e.currentTarget.dataset.name;
				let mmid = e.currentTarget.dataset.mmid;
				let value = e.detail.value;
				let purchase_unit_id = this.purchase_unit_mmid_obj[mmid][value].value;
				this.list[index].purchase_unit_id = purchase_unit_id;
				this.updataAllList();
			},
			updataAllList() {
				this.allList.forEach((v, i) => {
					let item = this.list.find(d => d.mm_id == v.mm_id);
					if (item) {
						this.allList[i] = JSON.parse(JSON.stringify(item));
					}
				})
			},
			msupplierPickerCancel(e) {
				this.msupplierPickerShow = false;
			},
			msupplierPickerConfirm(e) {
				let key = this.msupplierPickerKey;
				this.msupplierPickerShow = false;
				this.list[key].supplier_id = e.id;
				this.updataAllList();
			},
			openMsupplierPicker(e) {
				let key = e.currentTarget.dataset.name;
				this.msupplierPickerKey = Number(key);
				this.msupplierPickerShow = true;
			},
			checkboxChange(e) {
				if (e.length == this.list.length) {
					this.checkboxAllValue = [0];
				} else {
					this.checkboxAllValue = [];
				}
			},
			checkboxAllChange(e) {
				if (e.length == 0) {
					this.checkboxValue = [];
				} else {
					let checkboxValue = [];
					this.list.forEach((v, i) => {
						checkboxValue.push(i);
					})
					this.checkboxValue = checkboxValue;
				}
			},
			order() {
				if (this.checkboxValue.length == 0) {
					uni.$u.toast('请至少选择一项');
					return;
				}
				let list = this.list.filter((v, i) => this.checkboxValue.includes(i));
				let to_place_list = list.map(v => {
					return {
						'id': v.id,
						'mm_id': v.mm_id,
						'material_id':v.material_id,
						'purchase_unit_price': v.purchase_unit_price,
						'purchase_unit_id': v.purchase_unit_id,
						'purchase_unit_qty': v.purchase_unit_qty,
						'need_date': v.need_date,
						'supplier_id': v.supplier_id,
						'mbatch_int': v.mbatch_int,
						'org_pr_id': v.org_pr_pending_id[0],
						'cost_center_id': v.cost_center_id,
						'cus_group_id': v.cus_group_id
					}
				})
				uni.showLoading({
					title: '加载中'
				});
				purchaser_place_order({
					to_place_list: to_place_list
				}).then((res) => {
					uni.$u.toast('操作成功');
					setTimeout(() => {
						uni.$emit('refresh_index');
						uni.navigateBack({
							delta: 1
						});
					}, 2000)
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})

			},
			getData() {
				let po_pr_record_res = {};
				try {
					po_pr_record_res = uni.getStorageSync('po_pr_record');
				} catch (e) {}

				// uni.showLoading({
				// 	title: '加载中'
				// });
				// po_pr_record().then((res) => {
				let {
					org_pr_detail,
					org_pr_record
				} = po_pr_record_res;
				if (this.org_pr_id == 0) {
					org_pr_record = org_pr_record.filter(v => v.date == this.date);
					let org_pr_ids = org_pr_record.map(v => v.id);
					org_pr_detail = org_pr_detail.filter(v => org_pr_ids.includes(v.org_pr_pending_id[0]));
				} else {
					org_pr_detail = org_pr_detail.filter(v => v.org_pr_pending_id[0] == this.org_pr_id);
				}
				let org_pr_record_obj = {};
				org_pr_record.forEach(v => {
					org_pr_record_obj[v.id] = v;
				})
				this.checkboxValue = [];
				this.purchase_unit_qty = {};
				let cus_group_arr = [];
				let cost_center_arr = [];
				org_pr_detail.forEach((v, i) => {
					v.mm_id_name = v.mm_id[1];
					v.mm_id = v.mm_id[0];
					v.material_id = v.material_id[0];
					v.supplier_id_name = v.supplier_id[1];
					v.supplier_id = v.supplier_id[0];
					v.purchase_unit_id_name = v.purchase_unit_id[1];
					v.purchase_unit_id = v.purchase_unit_id[0];
					let pr = org_pr_record_obj[v.org_pr_pending_id[0]] || {};
					v.cost_center_id_name = pr.cost_center_id[1];
					v.cost_center_id = pr.cost_center_id[0];
					v.cus_group_id_name = pr.cus_group_id[1];
					v.cus_group_id = pr.cus_group_id[0];
					this.checkboxValue.push(i);
					this.purchase_unit_qty[v.mm_id] = v.purchase_unit_qty;
					this.purchase_unit_price[v.mm_id] = v.purchase_unit_price;
					this.price[v.mm_id] = v.purchase_unit_qty * v.purchase_unit_price;

					if (!cus_group_arr.find(d => d.value == v.cus_group_id)) {
						cus_group_arr.push({
							label: v.cus_group_id_name,
							value: v.cus_group_id,
						})
					}
					if (!cost_center_arr.find(d => d.value == v.cost_center_id)) {
						cost_center_arr.push({
							label: v.cost_center_id_name,
							value: v.cost_center_id,
						})
					}
				})
				this.list = org_pr_detail;
				this.allList = JSON.parse(JSON.stringify(org_pr_detail));
				this.cus_group_arr = cus_group_arr;
				this.cost_center_arr = cost_center_arr;
				this.filter.cost_center = cost_center_arr.map(v => v.value);
				this.filter.cus_group = cus_group_arr.map(v => v.value);
				this.old_filter = JSON.parse(JSON.stringify(this.filter));
				// console.log(cus_group_arr);
				// console.log(cost_center_arr);
				// }).catch(() => {

				// }).finally(() => {
				// 	uni.hideLoading();
				// 	uni.stopPullDownRefresh();
				// })
			},
			get_material() {
				let material_static_data = this.$store.getters.get_material_static_data;
				// console.log(material_static_data);
				let {
					daily_cost_category,
					material_top_category,
					material_purchase_category,
					material_purchase_unit_category,
					// msupplier,
					selection_fields,
					material_unit_ratio,
					stock_top_loc_category
				} = material_static_data;

				let material_purchase_unit_category_obj = {};
				material_purchase_unit_category.forEach(v => {
					material_purchase_unit_category_obj[v.id] = v;
				})
				this.material_purchase_unit_category = material_purchase_unit_category;
				this.material_purchase_unit_category_obj = material_purchase_unit_category_obj;

				material_create_edit({
					// need_day: this.need_day
				}).then((res) => {
					let {
						// daily_cost_category,
						// material_top_category,
						// material_purchase_category,
						// material_purchase_unit_category,
						msupplier,
						// selection_fields,
						// material_item,
						// material_unit_ratio,
						// stock_top_loc_category
					} = res.result;
					this.msupplierObj = {};
					msupplier.forEach(v => {
						v.data = JSON.parse(JSON.stringify(v));
						v.id = v.supplier_id[0];
						this.msupplierObj[v.id] = v;
					})
					this.msupplier = msupplier;

				}).catch(() => {

				}).finally(() => {

				})
				purchase_material_item().then((res) => {
					let material_item = res.result;
					this.material_item = material_item;
					let material_obj = {};
					material_item.forEach(v => {
						material_obj[v.id] = v;
					})
					this.material_obj = material_obj;
					this.set_purchase_unit_mmid_obj(material_unit_ratio);
					this.$store.commit('set_material_item', res.result);
				});

			},
			set_purchase_unit_mmid_obj(material_unit_ratio) {

				let purchase_unit_mmid_obj = {};
				material_unit_ratio.forEach(v => {
					try {
						let material_id = v.material_id[0];
						let mmid = this.material_obj[material_id].mm_id[0];
						if (!purchase_unit_mmid_obj[mmid]) {
							purchase_unit_mmid_obj[mmid] = [];
						}
						purchase_unit_mmid_obj[mmid].push({
							...v,
							label: v.unit_id[1],
							value: v.unit_id[0]
						})
					} catch (e) {
						//TODO handle the exception
						// console.log(e)
					}
				});
				// console.log('----------');
				// console.log(purchase_unit_mmid_obj[1112]);
				this.purchase_unit_mmid_obj = purchase_unit_mmid_obj;

			}
		},

		onLoad(d) {
			this.date = d.date || '2024-02-29';
			this.org_pr_id = d.org_pr_id || 0;
			this.get_material();
			this.getData();
		},
		onShow() {
			// this.role = this.$store.getters.get_role;
			// this.isChef = this.$store.getters.get_role == 'chef';
			// this.isPurchaser = this.$store.getters.get_role == 'purchaser';
			// this.getData();
		},
		onReady() {

		},
		onPullDownRefresh() {
			this.getData();
		}
	}
</script>

<style lang="scss" scoped>
	.blank {
		height: calc(60rpx + 40px);
	}

	.btn-confirm {
		height: 90upx;
		line-height: 90upx;
		width: 200upx;
		text-align: center;
		background-color: #675f91;
		color: #ffffff;
	}

	/deep/.col-item {
		padding: 20upx 20upx;
		// text-align: center;
	}

	/deep/.input_border_bottom {
		line-height: 72upx;
		height: 72upx;
		font-size: 28upx;
		border-bottom: 1px solid #cccccc;
	}
</style>